#include <stdlib.h>
#include "star.h"

#define MOTION_BLUR_SIZE 3

glm::vec3 Star::farAwayColor(0, 0, 0);
glm::vec3 Star::nearColor(1, 1, 1);


Star::Star()
: _pos(0.f, 0.f, 1.f)
{
}


void Star::randomizePos()
{
	_pos.x = rand() / (float)RAND_MAX;
	_pos.y = rand() / (float)RAND_MAX;
	do { // Avoid z = 0
		_pos.z = rand() / (float)RAND_MAX;
	} while (_pos.z == 0);

	if (rand() & 1)
		_pos.x = -_pos.x;
	if (rand() & 1)
		_pos.y = -_pos.y;
}


void Star::draw(sdl::Surface* s)
{
	// Focal length of camera
	float f = s->getHeight() / 2.0f;
	// Update motion blur list
	_zettas.push_back(_pos.z);
	if (_zettas.size() > MOTION_BLUR_SIZE) {
		_zettas.pop_front();
	}
	// Draw with motion blur
	float percent = 1.0f / _zettas.size();
	float mult = percent;
	std::list<float>::const_iterator i = _zettas.begin();
	for (; i != _zettas.end(); ++i) {
		// Project coordinates 3D->2D
		float u = f * _pos.x / *i + (s->getWidth() >> 1);
		float v = f * _pos.y / *i + (s->getHeight() >> 1);
		// Draw with interpolated color
		s->putPixel(u, v, glm::mix(nearColor, farAwayColor, *i) * mult);
		mult += percent;
	}
}


void Star::move(float velocity) {
	_pos.z -= velocity;
	if (_pos.z <= 0)
		_pos.z += 1;
}

